package com.merceria

class ArticuloController {


	def list(Integer max){
		
		params.max = Math.min(max ?:10, 100)
		
		[articuloInstanceList: Articulo.list(), articuloInstanceTotal: Articulo.count()]
	}
	
	def create()
	{
		[articuloInstance:new Articulo(params)]
	}
	
	def show(Long id)
	{
		def articuloInstance = Articulo.get(id)
		
		if(!articuloInstance)
		{
			flash.message = "Articulo " + id + " no encontrado."
			redirect(action:'list')
			return
		}
		
		[articuloInstance:articuloInstance]
	}
	
	def edit(Long id)
	{
		def articuloInstance = Articulo.get(id)
		
		if(!articuloInstance)
		{
			flash.message = "Articulo " + id + " no encontrado."
			redirect(action:'list')
			return
		}
		
		[articuloInstance : articuloInstance]
	}
	
	def update(Long id, Long version)
	{
		def articuloInstance = Articulo.get(id)
		if(!articuloInstance)
		{
			flash.message = "Articulo " + id + " no encontrado."
			redirect(action:'list')
			return
		}
		
		if(version != null)
		{
			if(articuloInstance?.version > version)
			{
				flash.message = "El articulo " + id + " ha sido modificaco por otro usuario."
				render(view:"edit", model:[articuloInstance : articuloInstance])
				return
			}
		}
		
		articuloInstance.properties = params
		
		if(!articuloInstance.save(flush:true))
		{
			render(view:'edit', model:[articuloInstance : articuloInstance])
			return
		}
		
		flash.message = "El articulo ha sido actualizado."
		redirect(action:'show', id:articuloInstance.id)
	}
	
	def save()
	{
		def articuloInstance = new Articulo(params)
		
		articuloInstance.ultimaActualizacion = new Date()
		articuloInstance.ultimaActualizacionPrecio = new Date()
		
		def tipoArticuloInstance = TipoArticulo.get(params.tipo.id)
		tipoArticuloInstance.ultimoNumeroAsignado = params.numeroArticulo.toLong()
		
		if(!tipoArticuloInstance.save(flush:true))
		{
			flash.message = 'Tipo Articulo no pudo ser actualizado'
			render(view:'create', model:[articuloInstance:articuloInstance])
		}
		
		if(!articuloInstance.save(flush:true) )
		{
			render(view:'create', model:[articuloInstance:articuloInstance])
			return
		}
		
		flash.message = 'Articulo Creado'
		redirect(action:'show', id:articuloInstance.id)
	}
	
	def borrar()
	{
		def articulo = Articulo.findById(params.id.toLong())
		
		articulo.delete()
		
		redirect(controller:'buscador', action:"buscador")
	}
}
